<template>
    <Modal
        :title="modalTitle"
        v-model="modalOpen"
        @on-cancel="cancel"
        :width="500"

    >
        <div class="addDepToExempt">
            <Form ref="formData" :model="formData" :label-width="80" :rules="formRules">

                <Row >
                    <Col span="12">
                        <FormItem label="年份" prop="yearDate">
<!--                            <Input clearable v-model="formData.year" placeholder />-->
                            <DatePicker v-model="formData.yearDate" type="year" @on-change="handleChange" value-format="yyyy"
                                        placeholder="Select year" :disabled="formData.edit" style="width: 200px">
                            </DatePicker>
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span="12">
                        <FormItem label="整体限额" prop="limitAmt">
                            <RuiNumber clearable :precision="2" v-model="formData.limitAmt" max="1000000000" type="currency"
                                        class="input" placeholder/>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="12">
                        <FormItem label="费用类型" prop="costType">
                            <Select v-model="formData.costType" clearable placeholder="请选择" :disabled="formData.edit"
                                    class="input" filterable>
                                <Option v-for="(item,index) in dataDict.exemptFeeTypeDict" :value="item.value"
                                        :key="index">{{item.title}}
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Form-item label="所属部门" prop="departmentTitle">
                        <Poptip trigger="click" placement="right" title="选择部门" width="250" @on-popper-show="searchDp"
                                :disabled="formData.edit">
                            <div style="display:flex;">
                                <Input v-model="formData.departmentTitle" style="margin-right:10px;"
                                       :disabled="formData.edit" placeholder class="input"/>
                                <Button icon="md-trash" @click="clearSelectDep" :disabled="formData.edit">清空已选</Button>
                            </div>
                            <div slot="content" class="tree-bar">
                                <Input v-model="searchKey" suffix="ios-search" @on-change="searchDp"
                                       placeholder="输入部门名搜索" :disabled="formData.edit"/>
                                <Tree :data="dataDep" :load-data="loadDataTree" :disabled="formData.edit"
                                      @on-select-change="selectTree"></Tree>
                                <Spin size="large" fix v-if="dpLoading"></Spin>
                            </div>
                        </Poptip>
                    </Form-item>
                </Row>
                <row>
                    <Col span="150">
                        <div>
                            <Button type="primary" size="small" @click="handleSubmit('formData')"
                                    style="margin-left: 150px">保存
                            </Button>
                        </div>
                    </Col>
                </row>
            </Form>
        </div>
        <div slot="footer"></div>
    </Modal>
</template>

<script>
    import {
        saveDep,
    } from "@/projects/basic/api/contract/fee-waiver/exempt-configuration/index";
    import {
        initDepartment,
        loadDepartment,
        searchDepartment
    } from "@/projects/basic/api/admin/department";

    export default {
        // 已激活案件列表 弹窗
        name: "addDepToExempt",
        components: {},
        props: {
            isModalOpen: {
                type: Boolean,
                required: true
            },
            baseData: {
                type: Object,
                required: true
            },
            modalTitle: {
                type: String,
                required: true
            },
            dataDict: {
                type: Object,
                required: true
            },
            closeModal: {},



        },
        data() {
            return {
                modalOpen: this.isModalOpen,
                loading: false,
                searchKey: "",
                dpLoading: false, // 部门树加载
                formData: {
                    limitAmt: 0,
                    username: "",
                    year: '',
                    yearDate: null,
                    costType: '',
                    departmentTitle: "",
                    deptId: '',
                },
                dataDep: [],
                formRules: {
                    username: [
                        {required: true, message: "请选择"}
                    ],
                    yearDate: [
                        {required: true, message: "请输入"}
                    ],
                    limitAmt: [
                        {required: true, message: "请输入"}
                    ],
                    costType: [
                        {required: true, message: "请选择"}
                    ],
                    departmentTitle: [
                        {required: true, message: "请选择",trigger: 'change'}
                    ]
                },

            };
        },
        watch: {
            isModalOpen: function (newVal) {
                this.modalOpen = newVal
                if (newVal) {
                    this.$refs.formData.resetFields();
                    console.log('this.baseDatathis.baseData',this.baseData)
                    this.formData = Object.assign({},this.formData,this.baseData)
                    // this.isModalOpen = newVal;
                    this.loading = true;
                    console.log(this.formData,']]]]]',this.$refs.formData)
                }
            }
        },
        created() {

        },
        mounted() {
            this.init();
        },
        methods: {
            init() {
                this.initDepartmentTreeData();
            },
            cancel() {
                this.$emit("closeModal")
            },
            selectTree(v) {
                console.log(v,'========')
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let str = JSON.stringify(v[0]);
                    let data = JSON.parse(str);

                    this.formData.deptId = data.id;
                    this.formData.departmentTitle = data.title;
                }
            },
            initDepartmentTreeData() {
                let self = this;
                initDepartment().then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                            if (e.id === self.formData.deptId) {
                                e.selected = true;
                            }
                        });
                        this.dataDep.splice(0, this.dataDep.length);
                        this.dataDep.push(...res.data);
                    }
                });
            },
            handleChange(year) {
                this.formData.yearDate = year;
            },
            clearSelectDep() {
                this.formData.deptId = "";
                this.formData.departmentTitle = "";
            },
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        console.log(this.formData,"this.formData000020")
                        saveDep(this.formData).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("保存成功");
                            }
                            this.$emit("closeModal")
                        }).catch(() => {

                        });
                    } else {
                        this.$Message.error('保存失败!');
                    }
                })

            },
            loadDataTree(item, callback) {
                let self = this;
                loadDepartment(item.id).then(res => {
                    if (res.code === "0000") {
                        res.data.forEach(function (e) {
                            if (e.isParent) {
                                e.loading = false;
                                e.children = [];
                            }
                            if (e.status === '0') {
                                e.title = "[已禁用] " + e.title;
                                e.disabled = true;
                            }
                            if (e.id === self.formData.deptId) {
                                e.selected = true;
                            }
                        });

                        callback(res.data);
                    }
                });
            },
            searchDp() {
                // 搜索部门
                if (this.searchKey) {
                    this.dpLoading = true;
                    let self = this;
                    searchDepartment({title: this.searchKey}).then(res => {
                        this.dpLoading = false;
                        if (res.code === "0000") {
                            res.data.forEach(function (e) {
                                if (e.status === '0') {
                                    e.title = "[已禁用] " + e.title;
                                    e.disabled = true;
                                }
                            });
                            if (e.id === self.formData.deptId) {
                                e.selected = true;
                            }
                            this.dataDep.splice(0, this.dataDep.length);
                            this.dataDep.push(...res.data);
                        }
                    });
                } else {
                    this.initDepartmentTreeData();
                }
            },

        }
    };
</script>
<style scoped lang="less">
    .vertical-center-modal {
        display: flex;
        align-items: center;
        justify-content: center;

        .ivu-modal {
            top: 0;
        }
    }
    .input{
        width: 200px;
    }
    .ActivatedCase {
        .new-apply-table {
            padding-top: 18px;
        }

        .table-page {
            padding-top: 16px;
        }
    }

    .text-center {
        text-align: center;
    }
</style>
